
package com.compuvest.webstatus

import javax.servlet.ServletConfig
import javax.servlet.ServletException

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.annotation.WebServlet;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.InitialContext
import java.net.URLEncoder

import groovy.sql.Sql

//@WebServlet(name="HttpService",loadOnStartup=1,urlPatterns={"/webinfo/update"})
@WebServlet(name="HttpService",loadOnStartup=1,urlPatterns="/web/get")
class HttpService extends HttpServlet {

    private final static def log = Logger.getLogger(HttpService.class.getName());
    def sql

// <editor-fold defaultstate="collapsed" desc="init()">

    def void init(ServletConfig config) {
	super.init(config)

        def ds = new InitialContext().lookup("jdbc/mysql")
        sql = new Sql(ds)

        sql.eachRow('select VERSION()') {
            log.log(Level.INFO, "Init: sql version=${it[0]}");
        }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="processRequest()">

    def void processRequest(request, response) {

        def json
        switch(request.getParameter('exec')) {

            case 'advert':
                def time2 = refreshLeftMenu()
                break
            case 'leftmenu':
                json = '{}'
                break
            case 'util':
                switch(request.getParameter('ex')) {
                    //case 'getStatus'    : json = mysql.getGoogleItemsStatus(); break
                    //default: json = '{}'
                }
                break

            default: json = '{}'
        }

        response.setContentType("text/html;charset=UTF-8")
        response.getWriter().print(json)
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="refreshLeftMenu()">

//        ',s:[') AS CHAR)  gcat
    def final static MENU_CATEGORY =
        """SELECT category_id,CAST(CONCAT(
        '{id:',category_id,
        ',nm:',QUOTE(name),
        ',s:[') AS CHAR)  gcat
        FROM sklad.category
        WHERE publish=1 AND parent=0
        ORDER BY name"""

    def final static MENU_SUBCATEGORY =
        """SELECT CAST(IFNULL(GROUP_CONCAT(CONCAT(
        '{id:',category_id,
        ',nm:',QUOTE(name),
        '}')),'') AS CHAR) scat
        FROM sklad.category
        WHERE publish=1 AND parent=?
        ORDER BY name"""

    def final static UPDATE_LEFTMENU = "UPDATE sklad.environment SET content=? WHERE name='leftmenu'"

    def refreshLeftMenu() {

        def startEvent = System.currentTimeMillis()

        def menu = new StringBuilder()
        menu << '['

        def idx = 0
        sql.eachRow(MENU_CATEGORY)
        { row ->

            if(idx++) menu << ','
            menu << "${row.gcat}"

            menu << sql.firstRow(MENU_SUBCATEGORY, [row.category_id]).scat
            menu << ']}'
        }
        menu << ']'

        log.log(Level.INFO, "menu=\n${menu as String}");
        sql.executeUpdate(UPDATE_LEFTMENU, [menu as String])

        return System.currentTimeMillis() - startEvent
    }
// </editor-fold>



// <editor-fold defaultstate="collapsed" desc="benchmark()">
    // Time excecution
    def benchmark = { closure ->
        def start = System.currentTimeMillis()
        closure.call()
        return System.currentTimeMillis() - start
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="">
    def void doGet(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    def void doPost(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    String getServletInfo() {
        return "HttpService"
    }
    def void destroy() {
        sql = null
    }
// </editor-fold>
}
